package com.dfhc.pub.web;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.quickbundle.config.RmConfig;
import org.quickbundle.orgauth.IOrgauthConstants;
import org.quickbundle.orgauth.cache.RmFunctionNodeCache;
import org.quickbundle.orgauth.rmfunctionnode.vo.RmFunctionNodeVo;
import org.quickbundle.project.IGlobalConstants;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.common.vo.RmCommonVo;
import org.quickbundle.tools.helper.RmSqlHelper;
import org.quickbundle.tools.helper.RmStringHelper;
import org.quickbundle.tools.support.tree.DeepTreeVo;
import org.quickbundle.tools.support.tree.DeepTreeXmlHandler;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/pubController")
public class PubController  implements IGlobalConstants{
	
    @RequestMapping(value = "getParty")
    public String list(Model model, HttpServletRequest request) {
    	String view_id = request.getParameter("view_id");
		if(view_id == null || view_id.trim().length() == 0) {
			//view_id的默认值是RM_PARTY_VIEW表的第一条记录
			List<RmCommonVo> lPartyViewId = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT ID FROM RM_PARTY_VIEW ORDER BY ID", 1, 1);
			if(lPartyViewId.size() > 0) {
				view_id = lPartyViewId.get(0).getString("id");
			} else {
				view_id = IOrgauthConstants.PartyView.DEFAULT.id();			
			}
		}

		//优先获取parent_party_code
		String parent_party_code = request.getParameter("parent_party_code");
		
		//如果parent_party_code为null，获取parent_party_id且默认为""
		String parent_party_id = null;
		if(parent_party_code == null) {
			parent_party_id = request.getParameter("parent_party_id");
			if(parent_party_id == null) {
				parent_party_id = "";
			}
		}
		
		//是否包含自身，默认为0。只有懒加载时有效
		boolean include_self = false;
		include_self = "1".equals(request.getParameter("include_self"));
		
		//获取show_bk
		String[] aShow_bk = new String[0];
		String show_bk = request.getParameter("show_bk");
		if(show_bk != null && show_bk.trim().length() > 0) {
			String tempBk = show_bk.replaceAll("^,+", "").replaceAll(",+$", "");
			if(tempBk.trim().length() > 0) {
				aShow_bk = tempBk.trim().split(",");				
			}
		}
		
		//获取lazy_init，默认为1
		String lazy_init = request.getParameter("lazy_init");
		if(lazy_init == null || lazy_init.length() == 0 || (!"1".equals(lazy_init) && !"0".equals(lazy_init))) { 
			lazy_init = "0";
		}
		
		//查询树节点的sql语句
		StringBuilder sbSql = new StringBuilder();
		sbSql.append("select PR.PARENT_PARTY_ID, PR.CHILD_PARTY_ID, PR.PARENT_PARTY_CODE, PR.CHILD_PARTY_CODE, " +
				"PR.CHILD_IS_LEAF, PR.CHILD_PARTY_NAME, P.PARTY_TYPE_ID as CHILD_PARTY_TYPE_ID, PT.ICON as CHILD_ICON, " +
				"PT.BS_KEYWORD as CHILD_BS_KEYWORD, PR.CHILD_IS_MAIN_RELATION, PR.ORDER_CODE from RM_PARTY_RELATION PR " +
				"join RM_PARTY P on PR.CHILD_PARTY_ID=P.ID " +
				"join RM_PARTY_TYPE PT on P.PARTY_TYPE_ID=PT.ID where ");
		
		//懒加载，只获取1层子节点
		if("1".equals(lazy_init)) {
			//如果parent_party_code未指定，按parent_party_id查询
			if(parent_party_code == null) {
				if("".equals(parent_party_id)) {
					sbSql.append(" (PR.PARENT_PARTY_ID is null or PR.PARENT_PARTY_ID='')");
				} else {
					if(include_self) { //查自身
						sbSql.append(" PR.CHILD_PARTY_ID=" + parent_party_id);
					} else { //查父节点
						sbSql.append(" PR.PARENT_PARTY_ID=" + parent_party_id);
					}
				}
			} else { //parent_party_code不为空则按parent_party_code查询
				if("".equals(parent_party_code)) {
					sbSql.append(" (PR.PARENT_PARTY_CODE is null or PR.PARENT_PARTY_CODE='')");
				} else {
					if(include_self) { //查自身
						sbSql.append(" PR.CHILD_PARTY_CODE='" + parent_party_code + "'");
					} else { //查父节点
						sbSql.append(" PR.PARENT_PARTY_CODE='" + parent_party_code + "'");
					}
				}
			}
			//如果show_bk不为空，过滤
			if(aShow_bk.length > 0) {
				sbSql.append(" and PT.BS_KEYWORD in (" + RmStringHelper.parseToSQLStringApos(aShow_bk) + ")");
			}
		} else {
			//如果parent_party_code未指定，按parent_party_id查询
			if(parent_party_code == null) {
				StringBuilder sql_parentParty = new StringBuilder();
				sql_parentParty.append("select PR.CHILD_PARTY_CODE, PARENT_PARTY_CODE, CHILD_IS_MAIN_RELATION from RM_PARTY_RELATION PR where PR.PARTY_VIEW_ID=" + view_id);
				if("".equals(parent_party_id)) {
					sql_parentParty.append(" and (PR.PARENT_PARTY_ID is null or PR.PARENT_PARTY_ID='')");
				} else {
					sql_parentParty.append(" and PR.PARENT_PARTY_ID=" + parent_party_id);
				}
				List<String> lParentPartyCode = RmProjectHelper.getCommonServiceInstance().query(sql_parentParty.toString(), new RowMapper() {
				    public Object mapRow(ResultSet rs, int i) throws SQLException {
				    	return rs.getString("CHILD_PARTY_CODE");
				    }
				});
				int index = 0;
				if(lParentPartyCode.size() > 0) {
					for(String parentPartyCode : lParentPartyCode) {
						if(index == 0) {
							sbSql.append(" (PR.CHILD_PARTY_CODE like '" + parentPartyCode + "%'");
						} else {
							sbSql.append(" or PR.CHILD_PARTY_CODE like '" + parentPartyCode + "%'");
						}
						index ++;
					}
					sbSql.append(")");
				} else {
					sbSql.append(" PR.CHILD_PARTY_CODE like '" + NOT_EXIST_ID + "%'");
				}
			} else {
				sbSql.append(" PR.CHILD_PARTY_CODE like '" + parent_party_code + "%'");
			}
			//如果show_bk不为空，过滤
			if(aShow_bk.length > 0) {
				sbSql.append(" and PT.BS_KEYWORD in (" + RmStringHelper.parseToSQLStringApos(aShow_bk) + ")");
			}
		}
		sbSql.append(" and PR.PARTY_VIEW_ID=" + view_id); 
		List<RmCommonVo> lcvo = RmProjectHelper.getCommonServiceInstance().doQuery(sbSql.toString());
		model.addAttribute("beans", lcvo);
		model.addAttribute("last", lcvo.size());
		model.addAttribute("objKey", request.getParameter("objKey"));//form对应要回写的input的那么属性，第一个为要会写的id，
		model.addAttribute("fromName", request.getParameter("formName"));//from名称name属性
		model.addAttribute("view_id", view_id);//from名称name属性
		model.addAttribute("source", request.getParameter("source"));//标志请求从哪儿来的，source=orgBack：说明是后台组织结构
		if("orgBack".equals( request.getParameter("source"))){
			return "/ztree/radioBack";	
		}else{
			return "/ztree/radio";
		}
    	
    }
    
	
	/**
	 * 功能菜单按钮
	 * @param request
	 * @param orgTree
	 * @param authorityMenuTree
	 * @return
	 */
    @RequestMapping(value = "getMenuTree",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
	public Map  getMenuTree(Model model,HttpServletRequest request){
    	boolean authorityMenuTree=false;
    	if(request.getParameter("authorityMenuTree")==null  && ""==request.getParameter("authorityMenuTree")){
    	 	 authorityMenuTree=false;
    	}else{
    		 authorityMenuTree=Boolean.valueOf(request.getParameter("authorityMenuTree"));
    	}
   
		Map<String,Object> map=new HashMap<String,Object> ();
		DeepTreeXmlHandler dt = new DeepTreeXmlHandler();
		String totalCode =request.getParameter("total_code");
		String id =request.getParameter("id");
		if(totalCode==null){
			totalCode=""; 
		}
		if(!authorityMenuTree){
			//获取lazy_init，默认为1
			String lazy_init = request.getParameter("lazy_init");
			if(lazy_init == null || lazy_init.length() == 0 || (!"1".equals(lazy_init) && !"0".equals(lazy_init))) { 
				lazy_init = "1";
			}
			StringBuilder sql = new StringBuilder();
			sql.append("select ID,NODE_TYPE,ENABLE_STATUS,NAME,DATA_VALUE,TOTAL_CODE,IS_LEAF,ICON from RM_FUNCTION_NODE ");
			//启用禁用: 0=禁用,1=启用
			String enableStatus = request.getParameter("enable_status");
			//节点类型：1=子系统、一级模块,2=子模块、功能,3=页面按钮
			String nodeType = request.getParameter("node_type");
			//懒加载，只获取1层子节点
			if("1".equals(lazy_init)){
				sql.append(" WHERE ");
				if(RmStringHelper.checkNotEmpty(totalCode)){
					sql.append("TOTAL_CODE like '"+totalCode+"%' and ");
				}
				
				sql.append(" ");
				sql.append(RmSqlHelper.getFunction(RmSqlHelper.Function.LENGTH, RmConfig.getSingleton().getDatabaseProductName()));
				sql.append("(TOTAL_CODE) = "+(RmConfig.getSingleton().getDefaultTreeCodeFirst().length()+totalCode.length()));
				if(RmStringHelper.checkNotEmpty(enableStatus)&&"1".equals(enableStatus)) { 
					sql.append(" and ENABLE_STATUS='1'");
				}
				if(RmStringHelper.checkNotEmpty(nodeType)&&"3".equals(nodeType)){
					sql.append(" and NODE_TYPE!='3'");
				}
				sql.append(" order by ");
				sql.append(RmSqlHelper.getFunction(RmSqlHelper.Function.SUBSTR, RmConfig.getSingleton().getDatabaseProductName()));
				sql.append("(TOTAL_CODE, 1, ");
				sql.append(RmSqlHelper.getFunction(RmSqlHelper.Function.LENGTH, RmConfig.getSingleton().getDatabaseProductName()));
				sql.append("(TOTAL_CODE)-3)");
				sql.append(", ORDER_CODE");
				//sql.append(" order by TOTAL_CODE");

				List<RmCommonVo> lcvo = RmProjectHelper.getCommonServiceInstance().doQuery(sql.toString());
                if(totalCode.length()<7){
                	model.addAttribute("isParent", true);
				}
				map.put("lcvo", lcvo);
				model.addAttribute("beans", lcvo);
			}else{
				if(RmStringHelper.checkNotEmpty(enableStatus)&&"1".equals(enableStatus)) { 
					sql.append(" where ENABLE_STATUS='1'");
				}
				sql.append(" order by TOTAL_CODE");
				List<RmCommonVo> lcvo = RmProjectHelper.getCommonServiceInstance().doQuery(sql.toString());
				map.put("lcvo", lcvo);
				model.addAttribute("beans", lcvo);
			}
		} else { //从全局缓存读取菜单项
			List<String> lcvo = RmProjectHelper.getRmUserVo(request).getMenuList();
			List<Object> myTrees=new ArrayList<Object> ();
//			model.addAttribute("beans", lcvo);
			for(String thisCode : lcvo) {
				if(thisCode.startsWith(totalCode)) {
					RmFunctionNodeVo fnvo = RmFunctionNodeCache.getFunctionNode(thisCode);
					if(fnvo!=null){
						String hasChild = "1";
						DeepTreeVo dtv = new DeepTreeVo(thisCode, fnvo.getName(), hasChild, "");
						if(fnvo.getData_value()!=null && fnvo.getData_value().length()>0) {
//							String finalHref = RmUrlHelper.replaceParameter(fnvo.getData_value(), request);
							String finalHref = fnvo.getData_value();
							dtv.setHrefPath(request.getContextPath() + finalHref);
						}  
						dtv.setTarget("contentFrame");
						if(fnvo.getIcon() != null && fnvo.getIcon().startsWith("/")) {
							dtv.setLogoImagePath(request.getContextPath() + fnvo.getIcon());
						}
						if(thisCode.length() == totalCode.length() + RmConfig.getSingleton().getDefaultTreeCodeFirst().length()) {
							dt.addTreeNode(dtv);
						} else {
							dt.addTreeNode(thisCode.substring(0, thisCode.length()-RmConfig.getSingleton().getDefaultTreeCodeFirst().length()), dtv);
						}
					}
					myTrees.add(fnvo);
				}
			}
			map.put("lcvo", myTrees);
		}

	
		return map;
	}
    
 /**
  * 获取带有权限的功能菜单
  * @param model
  * @param request
  * @return
  */
  @RequestMapping(value = "getTreeOrg")  
  public String getTreeOrg(Model model,HttpServletRequest request){
//	  List list=new ArrayList();
//	    IRmCommonService cs = RmProjectHelper.getCommonServiceInstance();
	    List<String> codeList = RmProjectHelper.getRmUserVo(request).getMenuList();
	    if(codeList!=null && codeList.size()>0){
	    	StringBuilder sb=new StringBuilder();
	    	for(int i=0;i<codeList.size();i++){
	    		if(codeList.get(i)!=null && !"".equals(codeList.get(i))){
	    			sb.append("'");
	    			sb.append(codeList.get(i));
	    			sb.append("'");
	    			if(i<codeList.size()-1){
	    				sb.append(",");
	    			}
	    		}
	    	}
	   String sql = sqlJoinAuthorize_resource(RmProjectHelper.getRmUserVo(request).getParty_id_all(), "RM_FUNCTION_NODE", "RM_FUNCTION_NODE", "TOTAL_CODE", "RM_FUNCTION_NODE.ID, (select count(*) from RM_FUNCTION_NODE fn where fn.NODE_TYPE!='3' and fn.TOTAL_CODE like concat(RM_FUNCTION_NODE.TOTAL_CODE,'1%')) CHILD_COUNT, RM_FUNCTION_NODE.NODE_TYPE, RM_FUNCTION_NODE.ORDER_CODE, RM_FUNCTION_NODE.FUNCTION_PROPERTY, RM_FUNCTION_NODE.ENABLE_STATUS, RM_FUNCTION_NODE.NAME, RM_FUNCTION_NODE.DESCRIPTION, RM_FUNCTION_NODE.DATA_VALUE, RM_FUNCTION_NODE.TOTAL_CODE, RM_FUNCTION_NODE.IS_LEAF, RM_FUNCTION_NODE.ICON", " and RM_FUNCTION_NODE.TOTAL_CODE in (" + sb.toString() + ") and length(RM_FUNCTION_NODE.TOTAL_CODE)=6 and RM_FUNCTION_NODE.ENABLE_STATUS='1' and RM_FUNCTION_NODE.NODE_TYPE!='3' order by RM_FUNCTION_NODE.ORDER_CODE, SUBSTR(RM_FUNCTION_NODE.TOTAL_CODE,1,length(RM_FUNCTION_NODE.TOTAL_CODE)" + ")");
	   List<RmCommonVo> lvos = RmProjectHelper.getCommonServiceInstance().doQuery(sql);
	      	model.addAttribute("lvos", lvos);
	    }	
	  return "ztree/leftOrgZtree";
	  
  }
 public static String sqlJoinAuthorize_resource(String[] party_ids, String tableName,  String tableNameAlias, String joinColumnName, String selectStr, String whereOrderStr) {
					StringBuilder sb = new StringBuilder();
					//sb.append("select distinct(ar.OLD_RESOURCE_ID), ar.DEFAULT_ACCESS, ar.DEFAULT_IS_AFFIX_DATA, ar.DEFAULT_ACCESS_TYPE, ar.DEFAULT_IS_RECURSIVE, arr.AUTHORIZE_STATUS, arr.IS_AFFIX_DATA, arr.ACCESS_TYPE, arr.IS_RECURSIVE, ");
					sb.append("select distinct(ar.OLD_RESOURCE_ID), ");
					sb.append(selectStr);
					sb.append(" from RM_AUTHORIZE_RESOURCE ar left join RM_AUTHORIZE_RESOURCE_RECORD arr on ar.id=arr.AUTHORIZE_RESOURCE_ID join ");
					sb.append(tableName);
					sb.append(" ");
					sb.append(tableNameAlias);
					sb.append(" on ar.OLD_RESOURCE_ID=");
					sb.append(tableNameAlias);
					sb.append(".");
					sb.append(joinColumnName);
					sb.append(" where (ar.DEFAULT_ACCESS='1' or arr.PARTY_ID in(");
					sb.append(RmStringHelper.parseToSQLString(party_ids));
					sb.append(") )");
					sb.append(whereOrderStr != null ? whereOrderStr : "");
					return sb.toString();
				}
 
 /**
  * 根据total_code,获取该节点的下级菜单
  * @param model
  * @param reques
  * @return
  */
 @RequestMapping(value="getTreeOrgAjax",consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
 @ResponseBody
 public Map<String,Object> getTreeOrgAjax(Model model,HttpServletRequest request){
	String total_code= request.getParameter("total_code");
    List<String> codeList = RmProjectHelper.getRmUserVo(request).getMenuList();
	StringBuilder sb=new StringBuilder();
	for(int i=0;i<codeList.size();i++){
		if(codeList.get(i)!=null && !"".equals(codeList.get(i))){
			sb.append("'");
			sb.append(codeList.get(i));
			sb.append("'");
			if(i<codeList.size()-1){
				sb.append(",");
			}
		}
	}
	Map<String,Object> map=new HashMap<String,Object>();
	if(total_code==null || "".equals(total_code)){
		throw new RuntimeException("上级编码不可为空");
	}
	   String sql = sqlJoinAuthorize_resource(RmProjectHelper.getRmUserVo(request).getParty_id_all(), "RM_FUNCTION_NODE", "RM_FUNCTION_NODE", "TOTAL_CODE", "RM_FUNCTION_NODE.ID, (select count(*) from RM_FUNCTION_NODE fn where fn.NODE_TYPE!='3' and fn.TOTAL_CODE like concat(RM_FUNCTION_NODE.TOTAL_CODE,'1%')) CHILD_COUNT, RM_FUNCTION_NODE.NODE_TYPE, RM_FUNCTION_NODE.ORDER_CODE, RM_FUNCTION_NODE.FUNCTION_PROPERTY, RM_FUNCTION_NODE.ENABLE_STATUS, RM_FUNCTION_NODE.NAME, RM_FUNCTION_NODE.DESCRIPTION, RM_FUNCTION_NODE.DATA_VALUE, RM_FUNCTION_NODE.TOTAL_CODE, RM_FUNCTION_NODE.IS_LEAF, RM_FUNCTION_NODE.ICON", " and length(RM_FUNCTION_NODE.TOTAL_CODE)>6 and RM_FUNCTION_NODE.TOTAL_CODE like '"+total_code+"%'and RM_FUNCTION_NODE.TOTAL_CODE in("+sb+") and RM_FUNCTION_NODE.ENABLE_STATUS='1' and RM_FUNCTION_NODE.NODE_TYPE!='3' order by SUBSTR(RM_FUNCTION_NODE.TOTAL_CODE,1,length(RM_FUNCTION_NODE.TOTAL_CODE)" + "),RM_FUNCTION_NODE.ORDER_CODE");
	   List<RmCommonVo> lvos = RmProjectHelper.getCommonServiceInstance().doQuery(sql);
//	      	model.addAttribute("lvos", lvos);
     map.put("lvos", lvos);
	 return map;
 }
}
